package com.cgc999.host.service;

import android.app.IntentService;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;

import androidx.annotation.Nullable;

import com.cgc999.host.adapter.PromoteArticleListAdapter;
import com.cgc999.host.api.PromoteService;
import com.cgc999.host.vo.ContentInfoVo;
import com.cgc999.host.vo.PageResult;
import com.cgc999.host.vo.ResponseInfo;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.RequestBody;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * @CreateDate: 2020/1/9 17:26
 * @Description: java类作用描述
 * @Author: lgh
 */
public class MessageService extends Service {
    private final String TAG="MessageService";
    private Handler mHandler = new Handler();

    private Messenger mMessenger;

    private  Retrofit retrofit;

    private long articleNewNum=0;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (mMessenger == null) {
            mMessenger = (Messenger) intent.getExtras().get("messenger");
        }
        initData();
        Runnable runnable=new Runnable() {
            @Override
            public void run() {
                gainArticle(retrofit);
                Log.i(TAG,"articleNewNum:"+articleNewNum);
                long localNum=getNum();
                //判断是否有新增的文章
                if (localNum!=-1&&localNum<articleNewNum){
                    Message message = Message.obtain();
                    message.what = 1;
                    message.getData().putLong("num",articleNewNum-localNum);
                    try {
                        mMessenger.send(message);
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }
                mHandler.postDelayed(this,2000);
            }
        };
        mHandler.postDelayed(runnable, 0);
        return super.onStartCommand(intent, flags, startId);
    }

    private void initData(){
        retrofit=new Retrofit.Builder()
                .baseUrl("http://192.168.10.121:18011")
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private long getNum(){
        SharedPreferences sharedPreferences=getSharedPreferences("data", Context.MODE_PRIVATE);
        long size=sharedPreferences.getLong("articleNum",-1);
        Log.i(TAG,"articleNum:"+size);
        return size;
    }

    private void gainArticle(Retrofit retrofit){
        PromoteService promoteService=retrofit.create(PromoteService.class);
        String json="{   \n" +
                "\t\"open_id\": \"apUser180839080002\",\n" +
                "\t\"cur_page\":0\n" +
                "}";
        RequestBody body=RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),json);
        promoteService.gainContentHomeList(body)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe( new Observer<ResponseInfo<PageResult<ContentInfoVo>>>(){
                    @Override
                    public void onSubscribe(Disposable d) {
                        Log.i(TAG,"onSubscribe");
                    }

                    @Override
                    public void onNext(ResponseInfo<PageResult<ContentInfoVo>> s) {
                        ResponseInfo<PageResult<ContentInfoVo>> resultResponseInfo=s;
                        articleNewNum=resultResponseInfo.getData().getTotal();
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.i(TAG,"onError");
                    }

                    @Override
                    public void onComplete() {
                        Log.i(TAG,"onComplete");
                    }
                });
    }
}
